package com.heima.search.listen;

import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.vo.SearchArticleVO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author 壮哥
 * @Date 2021/10/10/15:24
 */
@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    ArticleSearchService articleSearchService;

    @RabbitListener(queuesToDeclare =@Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void addArticle(@Payload String articleId, Message message, Channel channel){
        log.info("搜索微服务 接收到添加文章到索引库信息==>  {}",articleId);
        try{
            ResponseResult<ApArticle> result = articleFeign.findArticle(Long.valueOf(articleId));
            if (result.getCode()!=0) {
                log.info("远程调用失败   findArticle:  {}", articleId);
                return;
        }
            ApArticle apArticle = result.getData();
            if (apArticle!=null){
                //执行保存索引库
                SearchArticleVO searchArticleVO = new SearchArticleVO();
                BeanUtils.copyProperties(apArticle,searchArticleVO);
                searchArticleVO.setLayout(apArticle.getLayout().intValue());
                articleSearchService.saveArticle(searchArticleVO);
            }


            //手动提交mq
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch(IOException e){
            e.printStackTrace();
        }
        log.info("成功更新索引信息  add:{}",articleId);
    }
    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void removeArticle(@Payload String articleId,Message message,Channel channel){
        log.info("搜索微服务 接收到删除索引库的消息==>{}",articleId);
        try {
            articleSearchService.deleteArticle(articleId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("成功更新索引信息   delete:{}",articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }
}
